package com.wkbb.basic.controller.open;

import com.github.pagehelper.PageInfo;
import com.wkbb.basic.model.Family;
import com.wkbb.basic.service.*;
import com.wkbb.basic.vo.FamilyManageEditVo;
import com.wkbb.common.constants.ErrorCode;
import com.wkbb.common.constants.RedisKeyConstant;
import com.wkbb.common.constants.VersionConstant;
import com.wkbb.common.dto.ResultDTO;
import com.wkbb.common.dto.basic.FamilyInfoDto;
import com.wkbb.common.dto.basic.StudentInfoDto;
import com.wkbb.common.dto.basic.UserDto;
import com.wkbb.common.dto.basic.UserInfoDto;
import com.wkbb.common.enums.RelationTypeEnum;
import com.wkbb.common.enums.RoleTypeEnum;
import com.wkbb.common.enums.SmsTypeEnum;
import com.wkbb.common.redis.RedisTemplateUtil;
import com.wkbb.common.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基础模块对外接口
 */
@RestController
@Api(description = "家长模块对外接口")
@RequestMapping("/basic/{apiVersion}/open")
@Slf4j
public class FamilyController {

    @Autowired
    private UserService userService;

    @Autowired
    private StudentService studentService;

    @Autowired
    private FamilyService familyService;

    @Autowired
    private RedisTemplateUtil redisTemplateUtil;

    @ApiOperation(value = "查询家长列表")
    @RequestMapping(value = "getFamilyInfoListByClassId", method = RequestMethod.GET)
    public ResultDTO<List<FamilyInfoDto>> getFamilyInfoListByClassId(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true, defaultValue = "1") @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "班级ID", required = false, defaultValue = "1") @RequestParam(name = "classId", required = false) Long classId) {
        log.info("***********FamilyController.getFamilyInfoListByClassId******apiVersion:{},orgId:{},classId:{}", apiVersion, orgId, classId);

        try {
            if (orgId == 0) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }

            Map<String, Object> params = new HashMap<>(2);
            params.put("orgId", orgId);
            params.put("classId", classId);

            return new ResultDTO<>(familyService.getFamilyInfoListByClassId(params));
        } catch (Exception e) {
            log.error("***********FamilyController.getFamilyInfoListByClassId******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "查询宝宝所有监护人信息")
    @RequestMapping(value = "/getGuardianInfo", method = RequestMethod.GET)
    public ResultDTO<List<UserInfoDto>> getGuardianInfo(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId
    ) {
        log.info("***********FamilyController.getGuardianInfo******apiVersion:{},userId:{}", apiVersion, userId);
        if (null == userId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        try {
            return new ResultDTO<List<UserInfoDto>>(studentService.getGuardianInfoList(userId));
        } catch (Exception e) {
            log.error("***********FamilyController.getGuardianInfo******", e);
        }
        return new ResultDTO<>(false);
    }

    @ApiOperation(value = "新增监护人信息")
    @RequestMapping(value = "/addGuardianInfo", method = RequestMethod.POST)
    public ResultDTO<Object> addGuardianInfo(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @RequestBody FamilyManageEditVo familyManageEditVo) throws Exception {
        log.info("***********FamilyController.addGuardianInfo******apiVersion:{},familyManageEditVo:{}", apiVersion, familyManageEditVo);
        if (null == familyManageEditVo) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }
        //前台传入的smsCode
        String smsCode = familyManageEditVo.getSmsCode();
        //获取redis短信验证码
        String key = RedisKeyConstant.WKBB_TC_SMS_VERIFY + "type:" + SmsTypeEnum.FACESMSCODE.getValue() + ":mobile:" + familyManageEditVo.getFamilyInfoDto().getMobile();
        String verifyCode = (String) redisTemplateUtil.get(key);
        if (null == verifyCode) {
            //如果缓存没验证码,直接返回
            return new ResultDTO<Object>(ErrorCode.COMMON_VALIDATE_CODE_NOT_EXIST_OR_INVALID);
        }
        if (!verifyCode.equals(smsCode)) {
            //验证码错误
            return new ResultDTO<Object>(ErrorCode.COMMON_VALIDATE_CODE_NOT_MATCH_PHONE);
        }

        FamilyInfoDto familyInfoDto = familyManageEditVo.getFamilyInfoDto();
        List<StudentInfoDto> studentInfoDtoList = familyManageEditVo.getStudentInfoDtoList();
        if (familyInfoDto == null) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        ErrorCode result = userService.checkMobileErrorCode(familyInfoDto.getMobile(), familyInfoDto.getCardNo(),
                null, null, RoleTypeEnum.FAMILY.getValue(), familyInfoDto.getOrgId(),null);
        if (result != null) {
            return new ResultDTO<>(result);
        }

        try {
            familyService.insert(familyManageEditVo, "小程序添加",true);
            //删除验证码
            redisTemplateUtil.delete(key);
            return new ResultDTO<Object>();
        } catch (Exception e) {
            log.error("***********FamilyController.getGuardianInfo******", e);
        }

        return new ResultDTO<>(false);
    }


    @ApiOperation(value = "根据年级班级查询家长分页列表")
    @RequestMapping(value = "/getFamilyPageByRole", method = RequestMethod.GET)
    public ResultDTO<PageInfo<FamilyInfoDto>> getFamilyPageByRole(
            @ApiParam(value = "接口版本", defaultValue = VersionConstant.V1, required = true) @PathVariable(name = "apiVersion") String apiVersion,
            @ApiParam(value = "组织ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "年级ID", required = false) @RequestParam(name = "gradeId", required = false) Long gradeId,
            @ApiParam(value = "班级ID", required = false) @RequestParam(name = "classId", required = false) Long classId,
            @ApiParam(value = "家长姓名", required = false) @RequestParam(name = "name", required = false) String name,
            @ApiParam(value = "手机号", required = false) @RequestParam(name = "mobile", required = false) String mobile,
            @ApiParam(value = "页码", required = false) @RequestParam(name = "pageNo", required = false, defaultValue = "1") Integer pageNo,
            @ApiParam(value = "每页条数", required = false) @RequestParam(name = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        try {
            HashMap<String, Object> params = new HashMap<>(6);
            params.put("orgId", orgId);
            params.put("gradeId", gradeId);
            params.put("classId", classId);
            params.put("name", name);
            params.put("mobile", mobile);
            return new ResultDTO<>(familyService.getFamilyInfoPageByClassId(params, pageNo, pageSize));
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultDTO<>(false);
        }
    }

    @ApiOperation(value = "根据家长手机号查询家长信息")
    @RequestMapping(value = "getFamilyInfoByMobile", method = RequestMethod.GET)
    public ResultDTO<FamilyInfoDto> getFamilyInfoByMobile(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "家长手机号", required = true, defaultValue = "1") @RequestParam(name = "mobile", required = true) String mobile
    ) {
        log.info("***********FamilyController.getFamilyInfoByMobile******apiVersion:{},mobile:{}", apiVersion, mobile);
        try {
            if (null == mobile) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            return new ResultDTO<>(familyService.getFamilyInfoByMobile(mobile));
        } catch (Exception e) {
            log.error("***********FamilyController.getFamilyInfoByMobile******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "根据家长userId查询家长列表")
    @RequestMapping(value = "getFamilyListByFamily", method = RequestMethod.GET)
    public ResultDTO<List<FamilyInfoDto>> getFamilyListByFamily(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学校ID", required = true) @RequestParam(name = "orgId", required = true) Long orgId,
            @ApiParam(value = "用户ID", required = true) @RequestParam(name = "userId", required = true) Long userId
    ) {
        log.info("***********FamilyController.getFamilyListByFamily******orgId:{},userId:{}", orgId, userId);
        try {
            if (null == userId || orgId == null) {
                return new ResultDTO<>(ErrorCode.PARAM_MISSING);
            }
            HashMap<String, Object> params = new HashMap<>();
            params.put("orgId", orgId);
            params.put("userId", userId);
            return new ResultDTO<>(familyService.getFamilyListByFamily(params));
        } catch (Exception e) {
            log.error("***********FamilyController.getFamilyListByFamily******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    @ApiOperation(value = "通过学生获取家长信息(取一位 若是有多人，按妈妈，爸爸,奶奶,爷爷的顺序设置)")
    @RequestMapping(value = "/getFamilyByStudent", method = RequestMethod.GET)
    public ResultDTO<UserInfoDto> getFamilyByStudent(
            @ApiParam(value = "接口版本", required = true, defaultValue = VersionConstant.V1) @PathVariable(value = "apiVersion", required = true) String apiVersion,
            @ApiParam(value = "学生ID", required = true) @RequestParam(name = "studentId", required = true) Long studentId) {

        log.info("***********FamilyController.getFamilyByStudent******apiVersion:{},accountId:{},openId:{}", apiVersion, studentId);

        if (null == studentId) {
            return new ResultDTO<>(ErrorCode.PARAM_MISSING);
        }

        try {

            List<UserInfoDto> list = studentService.getGuardianInfoList(studentId);
            if (list.size() == 1) {
                return new ResultDTO<UserInfoDto>(list.get(0));
            } else {

                //若是有多人，按妈妈，爸爸,奶奶,爷爷的顺序设置
                UserInfoDto userInfo = this.getUserInfo(list,RelationTypeEnum.MOTHER.getValue());
                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.FATHER.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.GRANDMA.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.GRANDPA.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.MATERNAL_GRANDMA.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.MATERNAL_GRANDPA.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.RELATIVE.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.GRAND_FATHER.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.GRAND_MOTHER.getValue());
                }

                if(null == userInfo)
                {
                    userInfo = this.getUserInfo(list,RelationTypeEnum.OTHER.getValue());
                }

                return new ResultDTO<>(userInfo);
            }

        } catch (Exception e) {
            log.error("***********FamilyController.getFamilyByStudent******", e);
            return new ResultDTO<>(ErrorCode.SYSTEM_EXCEPTION);
        }
    }

    private UserInfoDto getUserInfo(List<UserInfoDto> list,Integer relationType)
    {
        for(UserInfoDto userInfoDto : list)
        {
            if(userInfoDto.getRelationType().intValue() == relationType)
            {
                return userInfoDto;
            }
        }

        return null;
    }

}
